<template>
  <div style="margin-top: 50px">
    <el-form :model="value" ref="productAttrForm" label-width="85px" size="small">
      <el-form-item label="属性类型：">
        <el-select v-model="value.productAttributeCategoryId"
                   placeholder="请选择属性类型" @change="handleProductAttrChange" >
          <el-option
            v-for="item in productAttributeCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button size="small" @click="addProductAttrCate" type="primary">新增类型</el-button>
        <el-button size="small" @click="addNewSpec" type="primary">新增规格</el-button>
      </el-form-item>
      <el-form-item label="商品规格：">
        <el-card shadow="never" class="cardBg">
          <div v-for="(productAttr,idx) in selectProductAttr" v-bind:key="productAttr.index">
            {{productAttr.name}}：
            <el-checkbox-group v-if="productAttr.handAddStatus===0" v-model="selectProductAttr[idx].values">
              <el-checkbox v-for="item in getInputListArr(productAttr.inputList)" :label="item" :key="item"
                           class="littleMarginLeft"></el-checkbox>
            </el-checkbox-group>
            <div v-else>
              <el-checkbox-group v-model="selectProductAttr[idx].values">
                <div v-for="(item,index) in selectProductAttr[idx].options" v-bind:key="index" style="display: inline-block"
                     class="littleMarginLeft">
                  <el-checkbox :label="item" :key="item"></el-checkbox>
                  <el-button type="text" class="littleMarginLeft" @click="handleRemoveProductAttrValue(idx,index)">删除
                  </el-button>
                </div>
              </el-checkbox-group>
              <el-input v-model="addProductAttrValue" style="width: 160px;margin-left: 10px" clearable></el-input>
              <el-button class="littleMarginLeft" @click="handleAddProductAttrValue(idx)">增加</el-button>
            </div>
          </div>
        </el-card>
        <el-button
          type="primary"
          style="margin-top: 20px"
          size="medium"
          @click="handleRefreshProductSkuList">生成sku列表
        </el-button>
         <el-button
         v-if="isEdit"
          type="danger"
          style="margin-top: 20px"
          size="medium"
          @click="handleResaveProductSkuList">保存sku列表
        </el-button>
        <span>（修改商品规格和商品参数后，要点击保存sku列表按钮进行保存）</span>
        <el-table style="width: 100%;margin-top: 20px" :data="value.skuStockList" border>
          <el-table-column
            v-for="(item,index) in selectProductAttr"
            :label="item.name"
            :key="item.id"
            align="center">
            <template slot-scope="scope">
              {{getProductSkuSp(scope.row,index)}}
            </template>
          </el-table-column>
          <el-table-column
            label="销售价格"
            align="center">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.price"></el-input> -->
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
         
          <el-table-column
            label="商品编码"
            align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productCode"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="商品条形码"
            align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productBarCode"></el-input>
            </template>
          </el-table-column>
          <el-table-column v-if="isEdit"
            label="库存"
            align="center">
            <template slot-scope="scope">
              <span>{{scope.row.stock}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="绑定仓库"
            align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="handleEditDepot(scope.$index, scope.row)">编辑</el-button>
            </template>
          </el-table-column>
           <el-table-column
            label="属性图片"
            width="130"
            align="center">
            <template slot-scope="scope">
              <!-- <el-card shadow="never" class="cardBg" v-if="!isEdit">
                <div v-for="(item,index) in selectProductAttrPics" :key="index">
                  <single-upload v-model="item.pic" style="width: 100px;display: inline-block;">
                  </single-upload>
                </div>
              </el-card> -->
              <el-card shadow="never" class="cardBg">
                 <single-upload v-model="scope.row.pic" style="width: 100px;display: inline-block;" >
                  </single-upload>
              </el-card>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="handleRemoveProductSku(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- <el-button
          type="primary"
          style="margin-top: 20px"
          @click="handleSyncProductSkuPrice">同步价格
        </el-button> -->
      </el-form-item>
      <!-- <el-form-item label="属性图片：" v-if="hasAttrPic">
        <el-card shadow="never" class="cardBg">
          <div v-for="(item,index) in selectProductAttrPics" :key="index">
            <span>{{item.name}}:</span>
            <single-upload v-model="item.pic"
                           style="width: 300px;display: inline-block;margin-left: 10px"></single-upload>
          </div>
        </el-card>
      </el-form-item> -->
      <el-form-item label="商品参数：">
        <el-card shadow="never" class="cardBg">
          <div v-for="(item,index) in selectProductParam" :class="{littleMarginTop:index!==0}" :key="index">
            <div class="paramInputLabel">{{item.name}}:</div>
            <el-select v-if="item.inputType===1" class="paramInput" v-model="selectProductParam[index].value">
              <el-option
                v-for="item in getParamInputList(item.inputList)"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <el-input v-else class="paramInput" v-model="selectProductParam[index].value"></el-input>
            <el-button @click="addNewParams(item)">新增参数选项</el-button>
          </div>
        </el-card>
        
      </el-form-item>
      <el-form-item label="商品相册：">
        <p class="upload-tip">请上传 800*800px 的图片</p>
        <multi-upload v-model="selectProductPics" @input = "input"></multi-upload>
        <!-- <single-upload v-model="selectProductPics"></single-upload> -->
      </el-form-item>
      <el-form-item label="规格参数：">
        <el-tabs v-model="activeHtmlName" type="card">
          <el-tab-pane label="商品详情" name="pc">
            <tinymce :width="900" :height="300" v-model="value.detailHtml"></tinymce>
          </el-tab-pane>
          <el-tab-pane label="答疑&保障" name="mobile">
            <tinymce :width="900" :height="300" v-model="value.answerAnduarantee"></tinymce>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>

      <el-form-item style="text-align: center">
        <el-button size="medium" @click="handlePrev">上一步，填写商品促销</el-button>
        <!-- <el-button type="primary" size="medium" @click="handleNext">下一步，选择商品关联</el-button> -->
        <el-button type="primary" size="medium" @click="handleFinishCommit">完成，提交商品</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="编辑仓库信息" :visible.sync="isEditDepotOpen" :close-on-click-modal="false"  class="adjustmentBox">
        <!-- :show-close="true" -->
        <el-form ref="depotInfoForm" :model="depotInfoForm" class="depot-info">
          <el-form-item>
            <el-button @click="addDepotInfo">新增仓库</el-button>
          </el-form-item>
          <el-form-item
            v-for="(item, index) in depotInfoForm.depotItems"
            :label="'仓库' + (index+1)"
            :key="item.key"
            :rules="{
              required: true, message: '仓库信息不能为空', trigger: 'blur'
            }"
          >
            <el-select v-model="item.depotId" placeholder="请选择" @change="depotChange(item.depotId,index)">
              <el-option
                v-for="depot in value.depotList"
                :key="depot.name"
                :label="depot.name"
                :value="depot.id">
              </el-option>
            </el-select>
            <el-input v-model="item.stock" placeholder="库存数量" style="width:8rem;margin:0 1rem" @input="forceDepotNumUpdate($event)"></el-input>
            <el-button @click.prevent="removeCurDepot(item)">删除</el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="saveDepotInfo('depotInfoForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
          <el-button @click="closeDepotPop()">关闭</el-button>
        </div>
    </el-dialog>
    <el-dialog title="编辑商品规格信息" :visible.sync="isEditSpecOpen" :close-on-click-modal="false"  :before-close="refreshProductSpec"
    class="adjustmentBox">
      <product-attr-detail-spec :is-edit='false'></product-attr-detail-spec>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button @click="onSaveSpec" style="color:#fff;background-color:#417FF6;">保存</el-button>
        <el-button @click="isEditSpecOpen=false">关闭</el-button>
      </div> -->
    </el-dialog>
    <el-dialog title="编辑商品参数信息" :visible.sync="isEditParamsOpen" :close-on-click-modal="false"  :before-close="refreshProductSpec"
    class="adjustmentBox">
      <el-form :model="productAttrParams" :rules="rules" ref="productAttrParamsFrom" label-width="150px">
        <el-form-item label="属性值列表:">
          <!-- <el-input :autosize="true" type="textarea" v-model="inputListFormat"></el-input> -->
          <el-checkbox-group v-model="inputListFormat" v-if="inputListFormatModel.length>0">
            <el-checkbox v-for="attr in inputListFormatModel" :label="attr" :key="attr">{{attr}}</el-checkbox>
          </el-checkbox-group>
          <div>
            <el-input style="width:5rem;" type="text" v-model="newListItemVal"></el-input>
            <el-button @click="addOneFormat">新增</el-button>
            <span style="color:#666;">（只会保存被选中的选项）</span>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onParamsSubmit('productAttrParamsFrom')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%">
      <el-form ref="productAttrCatForm" :model="productAttrCate" :rules="rules" label-width="120px">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="productAttrCate.name" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('productAttrCatForm')">确 定</el-button>
      </span>
    </el-dialog>
    
  </div>
</template>

<script>
  import ProductAttrDetailSpec from '../../productAttr/components/ProductAttrDetail'
  import {fetchList as fetchProductAttrCateList} from '@/api/productAttrCate'
  import {fetchList as fetchProductAttrList,updateProductAttr,getProductAttr} from '@/api/productAttr'
 import SingleUpload from '@/components/Upload/singleUpload'
//  import SingleUpload from '@/components/Upload/single'
  import MultiUpload from '@/components/Upload/multiUpload'
  import Tinymce from '@/components/Tinymce'
 import {createProductAttrCate} from '@/api/productAttrCate'
 import {deleteSingleOldSku,deleteOldSkuids,updateEditSkuInfo} from '@/api/product';
  export default {
    name: "ProductAttrDetail",
    components: {SingleUpload, MultiUpload, Tinymce,ProductAttrDetailSpec,},
    props: {
      value: Object,
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        productAttributeCategoryIdCopy:0,//商品属性类型的id,编辑的时候，如果切换分类会有确认弹窗，如果取消的话，需要还原，所以把原来的copy一份
        isEditParamsOpen:false,//新增参数的value弹窗
        inputListFormat:[],
        productAttrParams:{},//新增参数
        inputListFormatModel:'',//新增参数
        newListItemVal:"",////新增参数的属性可选值
        paramId:null,//参数的id
        //isOkToSubmit:false,//是否可以点击最后的保存按钮
        dialogTitle:"",//新增属性类型弹窗的标题
        dialogVisible:false,//新增属性类型弹窗
         productAttrCate:{
          name:'',
          id:null
        },
        rules: {
          name: [
            { required: true, message: '请输入类型名称', trigger: 'blur' }
          ]
        },
        isEditSpecOpen:false,//新增规格弹窗
        activeDepotIndex: -1,//新增数据时，当前sku的index
        //编辑模式时是否初始化成功
        hasEditCreated:false,
        //商品属性分类下拉选项
        productAttributeCategoryOptions: [],
        //选中的商品属性
        selectProductAttr: [],
        //选中的商品参数
        selectProductParam: [],
        //选中的商品属性图片
        selectProductAttrPics: [],
        //可手动添加的商品属性
        addProductAttrValue: '',
        //商品富文本详情激活类型
        activeHtmlName: 'pc',
        activeSkuId:null,//编辑sku仓库的时候用
        depotInfoForm:{//编辑sku的库存信息使用
          depotItems:[
            {id:null,stock:0,depotId:null,depotName:""}
          ],
        },
        currentSkuIndex: null,//编辑仓库信息时候，为了不相互关联，所以用index来区分操作的是哪条数据
        isEditDepotOpen:false,//编辑sku的库存弹窗
        // depotInfoFormRule:{
        //   depotNameOfInfo:[
        //     {
        //       required: true, message: '仓库信息不能为空', trigger: 'blur'
        //     }
        //   ]
        // }
      }
    },
    computed: {
      //是否有商品属性图片
      hasAttrPic() {
        if (this.selectProductAttrPics.length < 1) {
          return false;
        }
        return true;
      },
      //商品的编号
      productId(){
        return this.value.id;
      },
      //商品的主图和画册图片
      selectProductPics:{
        get:function () {
          let pics=[];
          if(this.value.pic===undefined||this.value.pic==null||this.value.pic===''){
            return pics;
          }
          pics.push(this.value.pic);
          if(this.value.albumPics===undefined||this.value.albumPics==null||this.value.albumPics===''){
            return pics;
          }
          let albumPics = this.value.albumPics.split(',');
          for(let i=0;i<albumPics.length;i++){
            pics.push(albumPics[i]);
          }
          return pics;
        },
        set:function (newValue) {
          if (newValue == null || newValue.length === 0) {
            this.value.pic = null;
            this.value.albumPics = null;
          } else {
            this.value.pic = newValue[0];
            this.value.albumPics = '';
            if (newValue.length > 1) {
              for (let i = 1; i < newValue.length; i++) {
                this.value.albumPics += newValue[i];
                if (i !== newValue.length - 1) {
                  this.value.albumPics += ',';
                }
              }
            }
          }
        }
      }
    },
    created() {
      console.log(this.value.productAttributeCategoryIdCopy);
      this.getProductAttrCateList();
    },
    watch: {
      inputListFormat: function (newValue, oldValue) {

        newValue = newValue.join(",");
        this.productAttrParams.inputList = newValue;
      },
      value:{
        handler:function(newVal,oldVal){

          if(newVal.productAttributeCategoryId !=null){
            //productAttributeCategoryId
            this.handleEditCreated();
          }
        },
        immediate:true,//关键
        deep:true
      },
      productId:function (newValue) {
        if(!this.isEdit)return;
        if(this.hasEditCreated)return;
        if(newValue===undefined||newValue==null||newValue===0)return;
        this.handleEditCreated();
      },
      productAttributeCategoryId(newVal){
        if(newVal){
          this.getProductAttrList(1,newVal);
        }
      },
    },
    methods: {
      input(){
        console.log("***^^^^$%%%%%%%%%%%%%%%%%")
      },
      //新增参数属性值
      addOneFormat(){
        if(this.newListItemVal){
          this.inputListFormatModel.push(this.newListItemVal);
        }
        this.newListItemVal = '';
      },
      addNewParams(item){
        this.paramId = item.id;
        getProductAttr(this.paramId).then(response=>{
          if(response.code ==200){
            this.isEditParamsOpen = true;
             this.productAttrParams = response.data;
            //this.inputListFormat = this.productAttr.inputList.replace(/,/g,'\n');
            this.inputListFormat = this.productAttrParams.inputList.split(',');
            this.inputListFormatModel = JSON.parse(JSON.stringify(this.productAttrParams.inputList.split(',')));
          }
        })
      },
      onParamsSubmit(formName) {
        if(this.inputListFormat.length<1){
           this.$message({
            message: '请维护属性值列表',
            type: 'error',
            duration:1500
          });
          return
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否提交数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
                this.productAttrParams.inputType = 1;//改为列表选择
                updateProductAttr(this.paramId,this.productAttrParams).then(response=>{
                  this.isEditParamsOpen = false;
                  this.getProductAttrList(1, this.value.productAttributeCategoryId);
                });
            });
          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration: 1000
            });
            return false;
          }
        });
      },
      handleConfirm(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = new URLSearchParams();
            data.append("name",this.productAttrCate.name);
            if(this.dialogTitle==="添加类型"){
              createProductAttrCate(data).then(response=>{
                this.$message({
                  message: '添加成功',
                  type: 'success',
                  duration:1000
                });
                this.getProductAttrCateList();
                this.dialogVisible = false;
              });
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      addProductAttrCate() {
        this.dialogVisible = true;
        this.dialogTitle = "添加类型";
      },
      addNewSpec(){
        this.isEditSpecOpen= true;
      },
      refreshProductSpec(){
        if(this.value.productAttributeCategoryId !=null){
          this.handleProductAttrChange(this.value.productAttributeCategoryId);
        }
        this.isEditSpecOpen= false;
      },
      handleEditDepot(index,row){
        debugger
        if(this.isEdit){
           this.activeSkuId = row.id;
           this.activeDepotIndex = index;
          let tempMap = this.value.productSkuDepotParamMap;
          if(row.depotParamList){
            this.depotInfoForm.depotItems = row.depotParamList;
          }else if(tempMap[row.id] && tempMap[row.id].length>0 ){
            this.depotInfoForm.depotItems= JSON.parse(JSON.stringify(tempMap[row.id]));
          }else{
            this.depotInfoForm ={
             depotItems:[{id:null,stock:0,depotId:null,depotName:""}]
           };
          }
        }else{

         this.activeDepotIndex = index;
         if(row.depotParamList && row.depotParamList.length>0){
           this.depotInfoForm['depotItems'] = row.depotParamList;
         }else{
           this.depotInfoForm ={
             depotItems:[{id:null,stock:0,depotId:null,depotName:""}]
           };
         }
        }
        this.$forceUpdate();
        this.isEditDepotOpen = true;
      },
      removeCurDepot(item){
        var index = this.depotInfoForm.depotItems.indexOf(item)
        if (index !== -1) {
          this.depotInfoForm.depotItems.splice(index, 1)
        }
      },
      depotChange(newVal,index){
        let tempId = newVal;
        for( const item of this.value.depotList){
          if(item.id == tempId){
            this.depotInfoForm.depotItems[index].depotName = item.name;
          }
        };
        this.$forceUpdate();
      },
      saveDepotInfo(formName){
        let stockList = this.value.skuStockList;
        stockList[this.activeDepotIndex].depotParamList = this.depotInfoForm.depotItems;
        this.isEditDepotOpen = false;
      },
      closeDepotPop(){
       
        this.isEditDepotOpen = false;
      },
      forceDepotNumUpdate(){
        this.$forceUpdate();
      },
      addDepotInfo(){
        this.depotInfoForm.depotItems.push({
          id:null,
          stock:null,
          depotId:null,
          depotName:""
        });
        this.$forceUpdate();
      },
      handleEditCreated() {
        //根据商品属性分类id获取属性和参数
        if(this.value.productAttributeCategoryId !=null && !this.hasEditCreated){
          this.getProductAttrList(0, this.value.productAttributeCategoryId);
          this.getProductAttrList(1, this.value.productAttributeCategoryId);
        }
        this.hasEditCreated=true;
      },
      getProductAttrCateList() {
        let param = {pageNum: 1, pageSize: 100};
        fetchProductAttrCateList(param).then(response => {
          this.productAttributeCategoryOptions = [];
          let list = response.data.list;
          for (let i = 0; i < list.length; i++) {
            this.productAttributeCategoryOptions.push({label: list[i].name, value: list[i].id});
          }
        });
      },
      getProductAttrList(type, cid) {
        let param = {pageNum: 1, pageSize: 100, type: type};
        fetchProductAttrList(cid, param).then(response => {
          let list = response.data.list;
          if (type === 0) {
            this.selectProductAttr = [];
            for (let i = 0; i < list.length; i++) {
              let options = [];
              let values = [];
              if (this.isEdit) {
                if (list[i].handAddStatus === 1) {
                  //编辑状态下获取手动添加编辑属性
                  options = this.getEditAttrOptions(list[i].id);
                }
                //编辑状态下获取选中属性
                values = this.getEditAttrValues(i);
              }
              this.selectProductAttr.push({
                id: list[i].id,
                name: list[i].name,
                handAddStatus: list[i].handAddStatus,
                inputList: list[i].inputList,
                values: values,
                options: options
              });
            }
            if(this.isEdit){
              //编辑模式下刷新商品属性图片
              this.refreshProductAttrPics();
            }
          } else {
            this.selectProductParam = [];
            for (let i = 0; i < list.length; i++) {
              let value=null;
              if(this.isEdit){
                //编辑模式下获取参数属性
                value= this.getEditParamValue(list[i].id);
              }
              this.selectProductParam.push({
                id: list[i].id,
                name: list[i].name,
                value: value,
                inputType: list[i].inputType,
                inputList: list[i].inputList
              });
            }
          }
        });
      },
      //获取设置的可手动添加属性值
      getEditAttrOptions(id) {
        let options = [];
        for (let i = 0; i < this.value.productAttributeValueList.length; i++) {
          let attrValue = this.value.productAttributeValueList[i];
          if (attrValue.productAttributeId === id) {
            let strArr = attrValue.value.split(',');
            for (let j = 0; j < strArr.length; j++) {
              options.push(strArr[j]);
            }
            break;
          }
        }
        return options;
      },
      //获取选中的属性值
      getEditAttrValues(index) {
        let values = [];
        if (index === 0) {
          for (let i = 0; i < this.value.skuStockList.length; i++) {
            let sku = this.value.skuStockList[i];
            if (sku.sp1 != null && values.indexOf(sku.sp1) === -1) {
              values.push(sku.sp1);
            }
          }
        } else if (index === 1) {
          for (let i = 0; i < this.value.skuStockList.length; i++) {
            let sku = this.value.skuStockList[i];
            if (sku.sp2 != null && values.indexOf(sku.sp2) === -1) {
              values.push(sku.sp2);
            }
          }
        } else {
          for (let i = 0; i < this.value.skuStockList.length; i++) {
            let sku = this.value.skuStockList[i];
            if (sku.sp3 != null && values.indexOf(sku.sp3) === -1) {
              values.push(sku.sp3);
            }
          }
        }
        return values;
      },
      //获取属性的值
      getEditParamValue(id){
        for(let i=0;i<this.value.productAttributeValueList.length;i++){
          if(id===this.value.productAttributeValueList[i].productAttributeId){
            return this.value.productAttributeValueList[i].value;
          }
        }
      },
      // ifYouChange(){
      //   this.productAttributeCategoryIdCopy =  JSON.parse(JSON.stringify(this.value.productAttributeCategoryId));
      //   console.log(this.productAttributeCategoryIdCopy);
      // },
      handleProductAttrChange(value) {
        if(this.isEdit){//需要删除原来旧的sku ids
          this.$confirm('切换分类需要删除原有的sku，是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log(this.value.skuStockList);
            console.log(new Date().getMinutes())
            // if(this.value.skuStockList.lengh == 0) return;
            let delIds=[];
            this.value.skuStockList.map(item=>{
              if(item.id){
                delIds.push(item.id);
              }
            })
            if(delIds.length ==0 || this.value.skuStockList.lengh == 0){//都是新增的，不是原来就有的
              this.value.skuStockList =[];
               this.getProductAttrList(0, value);
                this.getProductAttrList(1, value);
              this.$forceUpdate();
              return;
            }
            deleteOldSkuids(delIds).then((res)=>{
              if(res.code ==200){
                this.value.skuStockList=[];
                // this.selectProductAttr = [];//页面上也清空数据，否则出现原来已删除的sku重现出现
                this.getProductAttrList(0, value);
                this.getProductAttrList(1, value);
                this.$forceUpdate();
              }
            })
          }).catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消删除'
            // });  
            this.value.productAttributeCategoryId = this.value.productAttributeCategoryIdCopy; 
          });
          return;
        }
        this.getProductAttrList(0, value);
        this.getProductAttrList(1, value);
      },
      getInputListArr(inputList) {
        console.log(inputList);
        console.log(this.selectProductAttr);
        return inputList.split(',');
      },
      handleAddProductAttrValue(idx) {
        let options = this.selectProductAttr[idx].options;
        if (this.addProductAttrValue == null || this.addProductAttrValue == '') {
          this.$message({
            message: '属性值不能为空',
            type: 'warning',
            duration: 1000
          });
          return
        }
        if (options.indexOf(this.addProductAttrValue) !== -1) {
          this.$message({
            message: '属性值不能重复',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        this.selectProductAttr[idx].options.push(this.addProductAttrValue);
        this.addProductAttrValue = null;
      },
      handleRemoveProductAttrValue(idx, index) {
        this.selectProductAttr[idx].options.splice(index, 1);
      },
      getProductSkuSp(row, index) {
        if (index === 0) {
          return row.sp1;
        } else if (index === 1) {
          return row.sp2;
        } else {
          return row.sp3;
        }
      },
      handleRefreshProductSkuList() {
        this.$confirm('刷新列表将导致sku信息重新生成，是否要刷新', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.isOkToSubmit = false;
          this.refreshProductAttrPics();
          this.refreshProductSkuList();
        });
      },
      handleSyncProductSkuPrice(){
        this.$confirm('将同步第一个sku的价格到所有sku,是否继续', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(this.value.skuStockList!==null&&this.value.skuStockList.length>0){
            let price=this.value.skuStockList[0].price;
            for(let i=0;i<this.value.skuStockList.length;i++){
              this.value.skuStockList[i].price=price;
            }
          }
          this.$forceUpdate();
        });
      },
      handleResaveProductSkuList(){
        debugger
        this.mergeProductAttrValue();
        if(this.toDelectOldSkuIds && this.toDelectOldSkuIds.length>0){
          deleteOldSkuids(this.toDelectOldSkuIds).then(res=>{
            if(res.code ==200){
              let tempObj={};
              tempObj.productAttributeValueList = this.value.productAttributeValueList;
              tempObj.productAttributeValueList.map((item)=>{
                item.productId = this.value.id;
              })
              tempObj.productId = this.value.id;
              tempObj.skuDepotStockInfoParams = this.value.skuStockList;
              tempObj.skuDepotStockInfoParams.map((item)=>{
                item.depotProductSkuList = item.depotParamList;
              })
               tempObj.skuDepotStockInfoParams.map((item)=>{
                delete item.depotParamList
              })
              updateEditSkuInfo(tempObj).then(response=>{
                if(response.code ==200){
                  this.$message({
                    message: 'sku修改成功',
                    type: 'success',
                    duration:1000
                  });
                  this.isOkToSubmit = true;
                }
              })
            }
          })
        }else{
          let tempObj={};
          tempObj.productAttributeValueList = this.value.productAttributeValueList;
          tempObj.productAttributeValueList.map((item)=>{
              item.productId = this.value.id;
          })
          tempObj.productId = this.value.id;
          tempObj.skuDepotStockInfoParams = this.value.skuStockList;
          tempObj.skuDepotStockInfoParams.map((item)=>{
            item.depotProductSkuList = item.depotParamList;
            //delete item.depotParamList
          })
          tempObj.skuDepotStockInfoParams.map((item)=>{
            delete item.depotParamList
          })
           
          // return ;
          tempObj.skuDepotStockInfoParams.map(item=>{
            item.price = item.price
          })
          updateEditSkuInfo(tempObj).then(response=>{
            if(response.code ==200){
              this.$message({
                message: 'sku修改成功',
                type: 'success',
                duration:1000
              });
               this.isOkToSubmit = true;
            }
          })
        }
      },
      refreshProductSkuList() {
        // let oldSkuStockList = JSON.parse(JSON.stringify(this.value.skuStockList)); //把原来的sku信息保存一份
        this.value.skuStockList = [];//清空当前sku信息
        // this.selectProductAttr = [];
        let len =this.selectProductAttr.length;//最后进行比较的时候，看看是比较sp1还是sp1,sp2,还是sp1,sp2,sp3
        let skuList = this.value.skuStockList;
         let tempArr=[];
        //只有一个属性时
        if (this.selectProductAttr.length === 1) {
          let values = this.selectProductAttr[0].values;
          for (let i = 0; i < values.length; i++) {
              let isContinue = true;
              // for(let m=0;m<oldSkuStockList.length;m++){
              //   if(oldSkuStockList[m].sp1 == values[i]){
              //     skuList.push(oldSkuStockList[m]);
              //     tempArr.push(oldSkuStockList[m]);
              //     isContinue = false;
              //     continue;
              //   }
              // }
              if(isContinue){
                skuList.push({
                  sp1: values[i],
                  depotParamList:[ {id:null,stock:0,depotId:null,depotName:""}],
                });
              }
          }
        } else if (this.selectProductAttr.length === 2) {
          let values0 = this.selectProductAttr[0].values;
          let values1 = this.selectProductAttr[1].values;
          for (let i = 0; i < values0.length; i++) {
            if (values1.length === 0) {
              skuList.push({
                sp1: values0[i],
                 depotParamList:[ {id:null,stock:0,depotId:null,depotName:""}],
              });
              continue;
            }
            for (let j = 0; j < values1.length; j++) {
              let isContinue = true;
              // for(let m=0;m<oldSkuStockList.length;m++){
              //   if(oldSkuStockList[m].sp1 == values0[i] && oldSkuStockList[m].sp2 == values1[j]){
              //     skuList.push(oldSkuStockList[m]);
              //     tempArr.push(oldSkuStockList[m]);
              //     isContinue = false;
              //     continue;
              //   }
              // }
              if(isContinue){
                skuList.push({
                  sp1: values0[i],
                  sp2: values1[j],
                  depotParamList:[
                    {id:null,stock:0,depotId:null,depotName:""}
                  ],
                });
              }
            }
          }
        } else {
          let values0 = this.selectProductAttr[0].values;
          let values1 = this.selectProductAttr[1].values;
          let values2 = this.selectProductAttr[2].values;
          for (let i = 0; i < values0.length; i++) {
            if (values1.length === 0) {
              skuList.push({
                sp1: values0[i],
                depotParamList:[ {id:null,stock:0,depotId:null,depotName:""}],
              });
              continue;
            }
            for (let j = 0; j < values1.length; j++) {
              if (values2.length === 0) {
                skuList.push({
                  sp1: values0[i],
                  sp2: values1[j],
                   depotParamList:[ {id:null,stock:0,depotId:null,depotName:""}],
                });
                continue;
              }
              for (let k = 0; k < values2.length; k++) {
                skuList.push({
                  sp1: values0[i],
                  sp2: values1[j],
                  sp3: values2[k],
                   depotParamList:[ {id:null,stock:0,depotId:null,depotName:""}],
                });
              }
            }
          }
        }
      
       
        // let oldSkuStockListIDs= oldSkuStockList.map((item)=>{return item.id});
        // let leftIds = tempArr.map((item)=>{return item.id});

        // for(let i =0;i<oldSkuStockListIDs.length;i++){
        //   for(let j =0;j<leftIds.length;j++){
        //     if(oldSkuStockListIDs[i]== leftIds[j]){
        //         oldSkuStockListIDs.splice(i,1)
        //     }
        //   }
        // }
        // //如果还有，说明有删除的id
        // if(oldSkuStockListIDs.length>0){
        //   this.toDelectOldSkuIds = oldSkuStockListIDs;
        // }
        this.value.skuStockList = skuList;
      },
      refreshProductAttrPics() {
        this.selectProductAttrPics = [];
        if (this.selectProductAttr.length >= 1) {
          let values = this.selectProductAttr[0].values;
          for (let i = 0; i < values.length; i++) {
            let pic=null;
            if(this.isEdit){
              //编辑状态下获取图片
              pic=this.getProductSkuPic(values[i]);
            }
            this.selectProductAttrPics.push({name: values[i], pic: pic})
          }
        }
      },
      //获取商品相关属性的图片
      getProductSkuPic(name){
        for(let i=0;i<this.value.skuStockList.length;i++){
          if(name===this.value.skuStockList[i].sp1){
            return this.value.skuStockList[i].pic;
          }
        }
        return null;
      },
      //合并商品属性
      mergeProductAttrValue() {
        this.value.productAttributeValueList = [];
        for (let i = 0; i < this.selectProductAttr.length; i++) {
          let attr = this.selectProductAttr[i];
          // if (attr.handAddStatus === 1 && attr.options != null && attr.options.length > 0) {
          if (attr.values.length > 0) {
            this.value.productAttributeValueList.push({
              productAttributeId: attr.id,
              value: this.getOptionStr(attr.values)
            });
          }
        }
        
        for (let i = 0; i < this.selectProductParam.length; i++) {
          let param = this.selectProductParam[i];
          this.value.productAttributeValueList.push({
            productAttributeId: param.id,
            value: param.value
          });
        }
      },
      //合并商品属性图片
      mergeProductAttrPics() {
        for (let i = 0; i < this.selectProductAttrPics.length; i++) {
          for (let j = 0; j < this.value.skuStockList.length; j++) {
            if (this.value.skuStockList[j].sp1 === this.selectProductAttrPics[i].name) {
              this.value.skuStockList[j].pic = this.selectProductAttrPics[i].pic;
            }
          }
        }
      },
      getOptionStr(arr) {
        let str = '';
        for (let i = 0; i < arr.length; i++) {
          str += arr[i];
          if (i != arr.length - 1) {
            str += ',';
          }
        }
        return str;
      },
      handleRemoveProductSku(index, row) {
        let list = this.value.skuStockList;
        console.log(list);
        if(this.isEdit && row.id){//编辑状态的sku，需要手动确认删除
          this.$confirm('是否确认删除该条sku?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            debugger
            deleteSingleOldSku(row.id).then(res=>{
              if(res.code ==200){
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
              }
            })
          }).catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消删除'
            // });          
          });
          //return;
        }
        if (list.length === 1) {
          list.pop();
        } else {
          list.splice(index, 1);
        }
      },
      getParamInputList(inputList) {
        return inputList.split(',');
      },
      handlePrev() {
        this.$emit('prevStep')
      },
      handleNext() {
        this.mergeProductAttrValue();
        this.mergeProductAttrPics();
        this.$emit('nextStep')
      },
      handleFinishCommit(){
        if(this.isOkToSubmit == false && this.isEdit){
          this.$message({
            message: '需要先保存sku，再进行保存',
            type: 'warning',
            duration: 1000
            });
            return
        }
        this.mergeProductAttrValue();
       // this.mergeProductAttrPics();
        this.$emit('finishCommit',this.isEdit);
      }
    }
  }
</script>

<style scoped>
  .littleMarginLeft {
    margin-left: 10px;
  }

  .littleMarginTop {
    margin-top: 10px;
  }

  .paramInput {
    width: 250px;
  }

  .paramInputLabel {
    display: inline-block;
    width: 100px;
    text-align: right;
    padding-right: 10px
  }

  .cardBg {
    background: #F8F9FC;
  }

  .depot-info{
    width: 30rem;
  }
  .depot-info >>> .el-form-item__content{
    display: flex;
  }
  .adjustmentBox >>> .form-container{
    width: 100%;
  }
  .el-table .cell .cardBg >>> .el-card__body{
    padding: 5px;
  }
  .upload-tip{
    color: red;
    font-size: 12px;
    line-height: 1;
  }
</style>
